<template>
	<view class="content">
		<!-- 404页面 -->
		<view class="noData" v-if="netWorkType == 'none'">
			<noData @handle="refresh"></noData>
		</view>
		<view v-if="netWorkType != 'none'">
			<tui-skeleton v-if="skeletonShow" backgroundColor="#fafafa" borderRadius="10rpx"></tui-skeleton>
			<view class="container tui-skeleton">

				<view class="cpt-mask" v-if="showMaskloading">
					<view class="mask-tip">
						<view style="display: flex;justify-content: center;">
							<image src="https://xoimg.aiouning.com/static/cash_loading.gif"
								style="width:120rpx;height: 120rpx;"></image>
						</view>
						<view class="txt">连接设备中,请耐心等待...</view>

						<tui-tag @tap="cancelConn()" style="position: relative; z-index: 99999999;" shape="circle"
							type="theme-blue">取消连接</tui-tag>
					</view>

				</view>
				<!-- 头部	 开始-->
				<view class="head-box marginleft15 marginright15">

					<view class="flex-box">
						<view class="head-list">
							<view v-if="data.userInfo.bindStatus&&JSON.stringify(data.check)!='{}'"
								class="bg-white padright15 border-radius8 padbottom5"
								style="margin-bottom: 24rpx;padding-left: 26rpx;">

								<view class="time">
									<view class="lf">{{data.check.create_time}}</view>
									<!-- <view class="rg">

									</view> -->
								</view>
								<view class="data-box   ">
									<view class="lf">
										<view class="word">{{data.check.glu}}</view>
									</view>
									<view class="rg">
										<view>
											<tui-tag v-if="data.check.status==1" size="small" padding="12rpx"
												type="green">正常</tui-tag>
											<tui-tag v-if="data.check.status==2" size="small" padding="12rpx"
												type="danger">低血糖</tui-tag>
											<tui-tag v-if="data.check.status==3" size="small" padding="12rpx"
												type="danger">高血糖</tui-tag>
										</view>
										<view class="word">
											{{data.check.unit_type_desc?data.check.unit_type_desc:''}}
										</view>

									</view>


								</view>
							</view>
							<view v-else class="bg-white padright15 border-radius8 padbottom15"
								style="margin-bottom: 24rpx;padding-left: 26rpx;">
								<view class="data-box  padtop10">
									<view class="lf">
										<view style="color:#6F6F6F;" class="word">- -</view>
									</view>

								</view>
							</view>
						</view>
						<view style="margin-top: 60rpx;">
							<tui-tag v-if="data.userInfo.bindStatus&&connected" shape="circle" type="theme-blue">已连接
							</tui-tag>
							<view v-if="!data.userInfo.bindStatus&&data.userInfo.deviceId!=''"
								:data-device-id="data.userInfo.deviceId" data-name="自动连接" @tap="checkBind($event)">
								<tui-tag shape="circle" type="theme-blue">连接设备</tui-tag>
							</view>
							<!--   @tap="checkBind($event)"   -->
							<view v-if="data.userInfo.bindStatus&&data.userInfo.deviceId!=''&&!connected"
								:data-device-id="data.userInfo.deviceId" data-name="自动连接" @tap="checkBind($event)">
								<!-- <tui-tag     shape="circle" type="theme-gray">设备断开</tui-tag> -->
								<tui-tag shape="circle" type="theme-blue">连接设备</tui-tag>
							</view>
							<view v-if="!data.userInfo.bindStatus&&data.userInfo.deviceId==''" @tap="searchDev()">
								<tui-tag shape="circle" type="theme-blue">连接设备</tui-tag>
							</view>

						</view>

					</view>

				</view>

				<!-- 头部	 结束-->
				<!--测试结果反馈	 开始-->
				<view class="res-box marginleft15 marginright15">
					<view class="flex-box margin-bottom20">
						<view class="item">
							<view class="font16 font-bold margin-bottom5">数据分析</view>

						</view>
						<view class="item" @tap="testResult">

							<view class="iconfont font14  word">
								&#xe6c1;测试说明
							</view>

						</view>
					</view>
					<view class="flex-box margin-bottom20 bg">
						<view class="res-list">
							<view class="border-radius8 pd">
								<view v-if="data.check.status==1" class="title">
									该成员今日测试数据正常,请继续保持良好的生活习惯,坚持做测试
								</view>
								<view v-else-if="data.check.status==2" class="title">
									该成员今日测试数据血糖偏低,请及时到医院检查
								</view>
								<view v-else-if="data.check.status==3" class="title">
									该成员今日测试数据血糖偏高,请及时到医院检查
								</view>
								<view v-else class="title">
									你暂未检测血糖数据
								</view>
							</view>

						</view>


					</view>
				</view>
				<!-- 测试结果反馈	 结束-->




				<!--图表	 开始-->
				<view class="week-trend  padbottom15 bg-white padtop15">
					<view class="flex-box padleft15 padright15">
						<text class="font16 font-bold">血糖波动趋势</text>
						<view>
							<!-- <text class="circle-icon margin-right5"></text> <text class="font12" font12>高压</text>
						<text class="circle-icon low margin-right5 marginleft15"></text> <text class="font12">低压</text> -->
						</view>
						<view class="viewMore font12 text-center" @tap="testRecord">

							<view>
								<text class="font14 font-gray2">查看更多数据</text>
								<text class="iconfont padleft5 font12 font-gray">&#xe62b;</text>
							</view>
						</view>
					</view>

					<view class="echart-view" v-if="showEchart">
						<view class="f2_container ">
							<canvas type="2d" class="f2-canvas" @touchStart="touchStart" @touchMove="touchMove"
								@touchEnd="touchEnd" />
						</view>
						<!-- <view class="line_chart">

							<canvas :canvasId="canvasId" id="canvasId" disable-scroll="true"
								:style="{ width: cWidth + 'px', height: cHeight + 'px','zindex':1 }"
								@touchstart="touchstart" @touchmove="touchmove" @touchend="touchend" />
							<slot />
						</view> -->
					</view>
					<!-- <view class="viewMore font12 text-center"  v-if="showEchart">
					<view class="btn  pad-all10 bg-body2 font-white" @tap="moreData">查看更多数据</view>
				</view> -->
				</view>
				<!-- 图表		 结束-->
				<!--文章	 开始-->

				<view class="relate-prod-list">
					<view class="flex-box font16 padbottom15 padleft15 padright15 font-bold padtop30"
						style="padding-left: 5px;">

						<!-- <view style="width:4px;height:20px;background-color:#3894FF;"></view> -->
						<view style="border-left: 4px solid #3894FF;padding-left: 15px; margin-left: -5px;">文章推荐</view>

						<view @tap="pageArticleList">
							<text class="font14 font-gray2">查看更多</text>
							<text class="iconfont padleft5 font12 font-gray">&#xe62b;</text>
						</view>
					</view>

					<view class="box bg-white marginleft15 marginright15 pad-all10 p-relative"
						v-for="(item,index) in data.article">
						<view class="flex-start-box" @click="articleDetail(item.id)">
							<view class="flex-item" style="flex-grow: 1;">
								<view class="title font12">
									{{item.title}}
								</view>
								<view style="position: absolute;bottom: 20rpx;display: flex;">
									<!-- <view class="font10 padtop10 padbottom5 font-gray" style="margin-top: 10rpx;">{{item.author}}</view> -->
									<view class="font10 font-gray">
										{{item.view_count}}人看过
									</view>
									<view class="font10 font-gray marginleft15">
										{{item.praise_num}}人点赞
									</view>
								</view>

							</view>
							<view class="right-img flex-item">
								<image :src="item.image"></image>
							</view>

						</view>
					</view>
				</view>
				<!-- 文章		 结束-->



			</view>

		</view>
		<uni-popup ref="conn" type="bottom" :bg="false" :custom="true">
			<view :style="{height:windowHeight,'margin-bottom':mBottom}" class="conn-box">

				<view class="flex-box">
					<view v-if="connStatus==0||connStatus==1" class="conn-list">
						<view style="text-align: center;color:#4299FF;font-size:60rpx;" class="iconfont  margintop10">
							&#xe737;</view>
						<view style="font-size:30rpx; text-align: center;" class="margintop10">正在搜索附近的蓝牙设备...</view>
						<view class="img">
							<!-- <image :src="OSS_HOST+'ble_search.gif'" ></image> -->
						</view>
					</view>
					<view v-if="connStatus>=2&&connStatus<30" style="margin-top: 150rpx;" class="conn-list">

						<view class="img2" v-if="connStatus==8">
							<image :src="OSS_HOST+'no_dev.png'"></image>
						</view>
						<view class="margintop10 word">{{errorMsg[connStatus].msg}}</view>
						<view class="margintop10 word1">{{errorMsg[connStatus].code}}</view>
						<view class="reconn">

							<tui-tag v-if="errorMsg[connStatus].connType=='create'" @tap="openBluetoothAdapter"
								shape="circle" type="theme-blue">再次连接</tui-tag>
							<view v-if="errorMsg[connStatus].connType=='reconnect'"
								:data-device-id="data.userInfo.deviceId" data-name="自动连接" @tap="checkBind($event)">
								<tui-tag shape="circle" type="theme-blue">
									重新连接
								</tui-tag>

							</view>

						</view>
						<view @tap="searchDev()"
							style="font-size: 28rpx; color:#82B5FF; text-align: center; margin-top: 40rpx;">重新获取蓝牙设备
						</view>
					</view>

					<view v-if="connStatus>=30" style="margin-top: 150rpx;" class="conn-list">

						<view class="img1">
							<image :src="OSS_HOST+'glu_measure.gif'"></image>
						</view>
						<view class="margintop10 word">{{errorMsg[connStatus].msg}}</view>
						<view class="margintop10 word1">{{errorMsg[connStatus].code}}</view>
						<view class="reconn">

							<tui-tag v-if="errorMsg[connStatus].connType=='create'" @tap="openBluetoothAdapter"
								shape="circle" type="theme-blue">再次连接</tui-tag>
						</view>
					</view>

				</view>
				<view v-if="connStatus==1" style="position:absolute;bottom:80rpx;width: 100%;" class="flex-box">
					<view class="conn-dev-list marginleft15 marginright15">

						<view class="bg-white border-radius8 pd">
							<scroll-view class="device_list" scroll-y scroll-with-animation>
								<view v-for="(item, index) in devices" :key="index" class="main-box">
									<!-- style="padding-top: 0px;" -->
									<view class="lf">{{ item.name }}</view>
									<view :data-device-id="item.deviceId" :data-name="item.name || item.localName"
										@tap="checkBind($event)" class="rg">
										<tui-tag margin="20rpx 20rpx 0 0" plain type="black">连接</tui-tag>
									</view>
								</view>

							</scroll-view>

						</view>

					</view>

				</view>
			</view>
		</uni-popup>
		<uni-popup ref="show" type="center">
			<uni-popup-dialog titleCss="remind" title="连接失败" content="请重新保持设备常亮,重新搜索设备并连接" :isClose="false"
				@confirm="confirm"></uni-popup-dialog>
		</uni-popup>
	</view>

</template>

<script>
	import {oss_host} from '@/config/config.js';
	import Vue from 'vue'
	import {
		fail
	} from 'assert';
	import store from '@/store/index.js';
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue'
	// 骨架屏
	import tuiSkeleton from "@/components/tui-skeleton/tui-skeleton"
	import tuiTag from '@/components/tag/tag'
	// import LineChart from '@/components/stan-ucharts/LineChart.vue';
	// import uCharts from '@/plugins/stan-ucharts/u-charts/u-charts.js';
	import F2 from '@/js_sdk/uni-f2/f2.min.js'

	function wrapEvent(e) {
		if (!e) return
		if (!e.preventDefault) {
			e.preventDefault = function() {}
		}
		return e
	}
	let chart = null
	const lineCharts = {},
		optionAs = {};
	import {
		mapGetters
	} from 'vuex';
	export default {
		components: {
			tuiSkeleton,
			tuiTag,
			// LineChart,
			uniPopup,
			uniPopupDialog
		},
		data() {
			return {
				echartsData: [],
				mBottom: '0px',
				OSS_HOST: oss_host,
				data: {
					article: [],
					userInfo: {
						bindStatus: false,
						deviceId: ''
					},
					check: {}
				},
				isAutoConn: false,
				//设备id
				deviceId: '',
				//服务id，这里根据自己的设备写死
				serviceId: '000000F0-0000-1000-8000-00805F9B34FB',
				//特征值id-----这里根据自己的设备写死
				characteristicId: '000000F6-0001-0008-0000-0805F9B34FB0',
				//设备名称
				deviceName: '',
				//存放蓝牙设备数组
				devices: [{
					'name': 222
				}, {
					'name': 333
				}],
				//查看是否连接
				connected: false,
				//存储当前连接状态，里面的value就是手机接收的值
				chs: [],
				//记录电脑向手机传递的数据
				myDataMeasure: [],
				//查询蓝牙适配器的开始时间
				_discoveryStarted: false,
				//是否可写
				canWrite: false,
				//要发送的数据
				sendData: '',
				//下部信息条的显示与隐藏(默认显示)
				infoShowHide: true,
				//隐藏和打开按钮的字
				infoShowHideButton: '隐藏',
				//用户对设备设置的基本参数
				myData: {
					myInterval: ''
				},
				//临时存储仪器传输的数据以及基本设置信息
				myMeatureDataPhone: [],
				//存放数据的key，等待网络好的时候通过key传递数据到服务器
				myTemplateKey: [],
				//记录存储数据的时间
				timeNow: '',
				// 骨架屏
				skeletonShow: false,
				//图表
				lineChartData: {

					label: [],
					value: [{
						name: '血糖',
						data: []
					}]

				},
				yAxisAs: {
					// disabled:false,
					max: 200,
					formatter: {
						type: 'number', //type:number percent String,额外参数:fixed:NUmber,name:String
						fixed: 0,
						name: ''
					}

				},
				canvasId: 'canvasMix',
				labelKey: 'label',
				valueKey: 'value',
				width: 750,
				height: 500,
				showEchart: false,
				showMaskloading: false,
				timeObj: '',
				connStatus: -1, //蓝牙连接状态  0 未连接  1 连接中  2 已连接  8 中断连接  9 绑定用户失败  10 获取蓝牙服务失败
				//connType  reconnect  重连   create  创建蓝牙连接
				errorMsg: {
					8: {
						msg: '搜索超时,检测未发现蓝牙设备...',
						code: '请确保蓝牙设备已开机,或处于连接状态',
						connType: 'create',
						src: ''
					},
					9: {
						msg: '用户绑定设备失败',
						code: '服务器繁忙,请重新连接设备',
						connType: 'create',
						src: ''
					},
					10: {
						msg: '连接蓝牙设备失败',
						code: '请打开设备,重新连接或重新获取蓝牙设备',
						connType: 'reconnect',
						src: ''
					},
					20: {
						msg: 'mol浓度值太低',
						code: 'mol浓度值太低',
						connType: 'reconnect',
						src: ''
					},
					21: {
						msg: 'mol浓度值太高',
						code: 'mol浓度值太高',
						connType: 'reconnect',
						src: ''
					},
					22: {
						msg: '测量上传失败',
						code: '测量上传失败',
						connType: 'reconnect',
						src: ''
					},
					30: {
						msg: '开始测量',
						code: '请把试纸插入到机器中保持设备常亮然后使用采血笔进行采血',
						connType: 'reconnect',
						src: ''
					},
					31: {
						msg: '请往试纸滴血',
						code: '请往试纸滴血',
						connType: 'reconnect',
						src: ''
					},
					32: {
						msg: '血液已经滴下等待结果',
						code: '血液已经滴下等待结果',
						connType: 'reconnect',
						src: ''
					},
				},
				isCancel: false
			};
		},
		created() {

			//进入后刷新ss
			// let val = {
			// 				blutdruck:'/',
			// 				dateformat:['09/02','09/01','08/31','08/30','08/29','08/28','08/27'],
			// 				health_num:0,
			// 				heart_num:0,
			// 				value:[{dp:0,heart:0,sp:0},{dp:0,heart:0,sp:0},{dp:0,heart:0,sp:0},{dp:0,heart:0,sp:0},{dp:0,heart:0,sp:0},{dp:0,heart:0,sp:0},{dp:0,heart:0,sp:0}]
			// 				};
			//      val = JSON.parse(JSON.stringify(val));
			// 		// console.log(val)
			// let sp = val.map(res => {

			// 	return res.sp
			// })
			// let dp = val.map(res => {
			// 	return res.dp
			// })


			// let arr = [{
			// 		name:'血糖',
			// 		data: [0,0,0,0,0,0,0]
			// 	}
			// ]
			// this.data.article= [{"id":128,"title":"更适合中老年人体质的血压计--西恩","image":"http://xoimg.aiouning.com/upload/202010/16/202010161551495f895115dcd48.png","praise_num":0,"view_count":0}]

			// this.$set(this.lineChartData, 'label', val.dateformat)
			// this.$set(this.lineChartData, 'value', arr)
			// console.log(this.lineChartData)
			// 		this.lineChart()
			// 		// console.log(this.lineChartData)
			// console.log('VUEX数据',this.myDataGlobal);
		},
		onHide() {
			// this.closeBluetoothAdapter()
		},
		onUnload() {
			this.closeBluetoothAdapter()
		},
		onPullDownRefresh() {
			setTimeout(() => {

				console.log('VUEX数据', this.myDataGlobal);
				console.log('VUEX数据时间间隔', this.myDataGlobal.myInterval);
				console.log('实际蓝牙数据', this.myData);
				console.log('实际蓝牙输入框数据', this.sendData);
				uni.showToast({
					title: '参数更新成功'
				});
				uni.stopPullDownRefresh();
			}, 1000);
		}, //注册网络状态
		computed: {
			//获取可使用窗口高度
			windowHeight() {

				return uni.getSystemInfoSync().windowHeight + 'px'
			},
			cWidth() {
				return uni.upx2px(this.width);
			},
			cHeight() {
				return uni.upx2px(this.height);
			},
			...mapGetters(['myDataGlobal', 'netWorkType'])
		},
		watch: {
			'myDataGlobal': {
				deep: true,
				immediate: true,
				handler() {
					//监听vuex数据变化，一旦变化及时取数据
					this.myData = this.myDataGlobal;
					//获取的第一个数据就是时间间隔，后两个数据就是获取的数量（目前是不能超过99组，到时候可以考虑设置时间间隔，分开发送这两个数据）
					this.sendData = ((Number(this.myData.myInterval)) * 10).toString() + this.myData.myNumber
				}
			}
		},

		mounted() {






		},
		methods: {
			initChart() {

				const query = uni.createSelectorQuery().in(this);
				query.select('.f2-canvas')
					.fields({
						node: true,
						size: true
					})
					.exec(res => {
						const {
							node,
							width,
							height
						} = res[0];
						const context = node.getContext('2d');
						const pixelRatio = wx.getSystemInfoSync().pixelRatio;
						// 高清设置
						node.width = width * pixelRatio;
						node.height = height * pixelRatio;
						const config = {
							context,
							width,
							height,
							pixelRatio
						};

						// // 实例化chart
						const chart = new F2.Chart(config)
						chart.legend(false)

						//数据源
						chart.source(this.echartsData);
						chart.scale('value', {
							min: 0,
							ticks: [0, 3, 6, 9]
						});
						chart.line().position('date*value').color('type');
						chart.render();

						if (chart) {
							this.chart = chart;
							this.canvasEl = chart.get('el');
						}
					});
			},
			onShow(e) {
				if (uni.getSystemInfoSync().platform == 'ios') {
					this.mBottom = '-34px';
				}

				this.getData();
			},
			getData() {
				let _this = this
				var opt = {
					url: '/blutdruck_check/index',
					data: {
						product_type: 3
					},
					success: function(res) {
						console.log(res)

						if (res.status) {
							// _this.$refs['conn'].close()

							_this.data.article = res.data.article
							_this.data.userInfo = res.data.userInfo
							_this.data.check = res.data.check
							_this.echartsData = res.data.echarts.value
							// let arr = [{
							// 	name: '血糖',
							// 	data: res.data.echarts.value
							// }]
							// _this.$set(_this.lineChartData, 'label', res.data.echarts.dateformat)
							// _this.$set(_this.lineChartData, 'value', arr)

							if (res.data.echarts) {
								_this.showEchart = true;
								// _this.lineChart();
								setTimeout(function() {
									_this.initChart();
								}, 1000)
							}

							//	console.log(_this.lineChartData)

							//第一次进来如果没有连接过设备则主动弹出蓝牙搜索页面
							if (!_this.data.userInfo.bindStatus) {
								_this.searchDev();
							}
							//设备断开以后不自动连接了 改成手动点击连接
							if (_this.data.userInfo.bindStatus && _this.connected == false) {
								//console.log(1111111111)
								//自动连接蓝牙设备
								_this.autoConn(_this.data.userInfo.deviceId)
							}

						} else {

							_this.connStatus = 22
						}
						//修复在测量状态下手机黑屏在唤起屏幕是出现趋势图问题
						if ((_this.connStatus == 30) || (_this.connStatus == 31) || (_this.connStatus == 32)) {
							_this.showEchart = false;
						}
					}
				};
				_this.$service.GetApi(opt)
			},
			//设备连接失败确定
			confirm() {
				this.$refs['show'].close()
				// this.$refs['show'].open()
			},
			searchDev() {
				this.showEchart = false;
				this.isCancel = false;
				this.$refs['conn'].open()
				this.connStatus = 1
				this.openBluetoothAdapter()

			},
			//发送存储中数据
			sendStorage() {
				uni.showLoading({
					title: '数据发送中...'
				});
				uni.getStorage({
					key: 'mykey',
					success: (res) => {
						this.myTemplateKey = res.data
						console.log('这是来自手机内存中的key', this.myTemplateKey);
					},
					fail: () => {
						console.log('key不存在，无法发送');
						this.myTemplateKey = [];
						return;
					}
				});
				//查询key
				console.log('数据存储的key：', this.myTemplateKey);
				for (let i = 0; i < this.myTemplateKey.length; i++) {
					console.log(`第${i}个:`, i)
					//打印storage中的文件
					uni.getStorage({
						key: this.myTemplateKey[i], //前后两次存的文件也都能找得到
						success: (res) => {
							console.log(`打印存储在storage中${i}的数据`, res.data);
						},
						fail: () => {
							console.log('该数据不存在');
						}
					});
				}
				//隐藏显示内容
				setTimeout(() => {
					uni.hideLoading();
					uni.showToast({
						title: '查询并发送成功'
					})
				}, 1000);
			},
			//为了去除重复的
			inArray(arr, key, val) {
				for (let i = 0; i < arr.length; i++) {
					if (arr[i][key] === val) {
						return i;
					}
				}
				return -1;
			},
			//清空本地存储
			clearLocalStorage() {
				uni.showModal({
					title: '警告',
					content: '确认删除本地数据?请确认数据已及时发送',
					success: function(res) {
						if (res.confirm) {
							uni.clearStorage();
							uni.showToast({
								title: '本地数据已清空'
							});
						} else if (res.cancel) {
							console.log('用户点击取消');
							return;
						}
					}
				});

			},
			//将本次接受的数据保存
			saveStorage() {
				//先向数组中添加基本的设置信息
				let date = new Date();
				this.timeNow = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate() + ' ' + date.getHours() +
					':' + date.getMinutes() + ':' + date.getSeconds();
				this.myMeatureDataPhone.push(this.timeNow);
				this.myMeatureDataPhone.push(this.myData.myInterval);
				this.myMeatureDataPhone.push(this.myData.myHomeStation);
				this.myMeatureDataPhone.push(this.myData.myOppositeStation);
				//将接收数据的数组进行合并
				this.myMeatureDataPhone = this.myMeatureDataPhone.concat(this.myDataMeasure);
				//查看新数组
				console.log('设置参数及数据数组内容：', this.myMeatureDataPhone);
				//查看本次的key
				console.log('本次的key:', this.myTemplateKey);
				//存储到本地storage中，并将key存到数组中，便于将来将数据获取后传递到服务器上。
				uni.setStorage({
					key: this.timeNow,
					data: this.myMeatureDataPhone,
					success: () => {
						this.myTemplateKey.push(this.timeNow);
						//提示数据保存成功
						uni.showToast({
							title: '数据保存成功'
						});
						//清空数组准备存下一组
						this.myMeatureDataPhone = [];
					},
					fail: () => {
						//提示数据保存失败
						uni.showToast({
							title: '数据保存失败',
							icon: 'none'
						});
					}
				});
			},
			//将本组的数据进行保存
			saveGroup() {
				//将key存储起来
				uni.setStorage({
					key: 'mykey',
					data: this.myTemplateKey,
					success: () => {
						uni.showToast({
							title: '本组已保存'
						});
						console.log('key存储成功')
					}
				});
			},
			// ArrayBuffer转16进度字符串示例
			str2ab1() {
				const buffer = new ArrayBuffer(4)
				const dataView = new DataView(buffer)
				dataView.setUint8(0, 0xA5)
				dataView.setUint8(1, 0x56)
				dataView.setUint8(2, 0x89)
				dataView.setUint8(3, 0x56)
				return buffer
			},
			//比大小
			myMax(n1, n2) {
				return Math.max(n1, n2)
			},
			//比长度
			myLen(arr) {
				arr = arr || []
				return arr.length
			},
			//显示隐藏下部信息条
			hideShowInfo() {
				this.infoShowHide = !this.infoShowHide;
				if (this.infoShowHideButton == '隐藏') {
					this.infoShowHideButton = '打开'
				} else {
					this.infoShowHideButton = '隐藏'
				}
			},
			//开启蓝牙适配器初始化蓝牙模块
			openBluetoothAdapter() {
				// console.log(9999999)
				//刷新蓝牙设备
				this.devices = []
				uni.openBluetoothAdapter({
					success: (res) => {
						console.log("开启蓝牙适配器成功(openBluetoothAdapter success)", res);
						this.startBluetoothDevicesDiscovery();
						uni.showToast({
							title: "开始扫描设备",
							icon: "success",
						});
					},
					fail: (res) => {
						uni.showToast({
							title: "请开启蓝牙",
							icon: "none",
						});
						if (res.errCode === 10001) {
							uni.onBluetoothAdapterStateChange(function(res) {
								//监听蓝牙适配器是否打开，若打开则自动搜索蓝牙设备(onBluetoothAdapterStateChange)
								if (res.available) {
									this.startBluetoothDevicesDiscovery();
								}
							});
						}
					},
				});
			},
			autoConn(deviceId) {
				uni.openBluetoothAdapter({
					success: (res) => {
						// console.log("开启蓝牙适配器成功(openBluetoothAdapter success)", res);
						// uni.showToast({
						//   title: "自动连接设备",
						//   icon: "success",
						// });
						this.isAutoConn = true
						this.createBLEConnection(deviceId, '自动连接')

					},
					fail: (res) => {
						uni.showToast({
							title: "请开启蓝牙",
							icon: "none",
						});
						if (res.errCode === 10001) {
							uni.onBluetoothAdapterStateChange((res) => {
								//监听蓝牙适配器是否打开，若打开则自动搜索蓝牙设备(onBluetoothAdapterStateChange)
								if (res.available) {
									this.createBLEConnection(deviceId, '自动连接')
								}
							});
						}
					},
				});
			},
			//开启蓝牙设备搜索
			startBluetoothDevicesDiscovery() {
				// 关闭蓝牙适配器的时候将其打开
				if (this._discoveryStarted) {
					return;
				}
				this._discoveryStarted = true;
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true, //允许重复上报同一个设备
					success: (res) => {
						console.log("开始搜寻蓝牙设备成功(startBluetoothDevicesDiscovery success)", res);
						uni.showLoading({
							title: "正在搜索设备",
						});
						this.onBluetoothDeviceFound();
					},
				});
			},
			//监听寻找到新设备的事件
			onBluetoothDeviceFound() {
				uni.onBluetoothDeviceFound((res) => {
					if (res) {
						uni.hideLoading();
					}
					res.devices.forEach(device => {
						//过滤掉没有名字的设备
						if (!device.name && !device.localName) {
							return
						};
						//这么操作是为了去除重复
						const foundDevices = this.devices //将数据中的数组复制一份,利用动态绑定方式，不断复制最新的数组
						const idx = this.inArray(foundDevices, 'deviceId', device.deviceId)
						if (idx === -1) {
							this.devices.push(device); //数组里没有的的就向里面添加数据，保证没有重复[uni写法]
						}
					})
					console.log(this.devices);
				});
			},
			//【点击某个蓝牙设备时】将目前你点击的设备作为对象e传递进来
			async checkBind(e) {
				console.log('createBLEConnection', e)
				this.isCancel = false;
				const _this = this
				const ds = e.currentTarget.dataset

				//绑定小程序与设备关系。
				const resp = await new Promise((resolve, reject) => {
					if (_this.data.userInfo.bindStatus) {
						resolve({
							status: 0,
							data: {
								bindStatus: true
							}
						})
					} else {
						//获取用户信息
						var opt = {
							url: '/wifi/bindDev',
							data: {
								dev_type: 2,
								mac: ds.deviceId
							},
							success: function(res) {
								//console.log(res)
								resolve(res)

							}
						};
						_this.$service.GetApi(opt)
					}


				})
				//  console.log(999999999999999999999999999999999)
				// console.log(resp)
				if (resp.status) {
					//初始用户绑定设备数据关系
					_this.data.userInfo.bindStatus = true
					_this.data.userInfo.deviceId = ds.deviceId
					//设备绑定成功
					_this.createBLEConnection(ds.deviceId, ds.name)


					//this.stopBluetoothDevicesDiscovery()//此时停止蓝牙搜索
				} else {


					//设备绑定成功
					if (typeof resp.data.bindStatus != "undefined" && resp.data.bindStatus) {

						//设备绑定成功
						_this.createBLEConnection(ds.deviceId, ds.name)
					} else {
						//设备已绑定失败
						this.connStatus = 9
					}
				}
			},
			createBLEConnection(deviceId, deviceName) {
				// console.log(88888888)
				// console.log(deviceId)
				const _this = this
				_this.showMaskloading = true
				setTimeout(() => {
					_this.showMaskloading = false
				}, 1000 * 30);
				//将现在点击的设备id传递进去
				this.deviceId = deviceId
				//将设备名称也传递给全局变量
				this.deviceName = deviceName
				//设备绑定成功
				uni.createBLEConnection({
					//这个deviceId不能删除，否则会报错【从这里往后要放一放】
					deviceId: this.deviceId,
					success: (res) => {
						this.connected = true,
							this.showMaskloading = false

						// console.log("设备已经连接(createBLEConnection)");
						console.log('连接时获取设备id', this.deviceId);
						setTimeout(() => {
							this.characteristicId = '000000F6-0001-0008-0000-0805F9B34FB0'
							this.getBLEDeviceServices(this.deviceId);
						}, 1000); //这里必须要延迟才行这是一个bug
					},
					fail: (err) => {
						this.stopBluetoothDevicesDiscovery() //此时停止蓝牙搜索
						if (this.isCancel == true) {
							return;
						}
						//自动连接蓝牙,打开状态
						this.showEchart = false;
						this.$refs['conn'].open()

						if (_this.data.userInfo.bindStatus) {
							this.connStatus = 10
						} else {
							this.connStatus = 8
						}
						this.showMaskloading = false
						return
					}
				})

				uni.onBLEConnectionStateChange((res) => {
					if (res.connected == false) {
						_this.connected = false
						if (_this.data.userInfo.bindStatus) {
							this.connStatus = 10
						} else {
							this.connStatus = 8
						}

					}
					console.log('连接状态:' + JSON.stringify(res))
				})
				this.stopBluetoothDevicesDiscovery() //此时停止蓝牙搜索
			},
			//获取蓝牙设备所有服务（走到这一步证明已经找到服务）
			getBLEDeviceServices(deviceId) {
				uni.getBLEDeviceServices({
					deviceId: deviceId,
					success: (res) => {
						// for (let i = 0; i < res.services.length; i++) {
						// 	if (res.services[i].isPrimary) {
						// 		//将服务id存储添加到全局服务id数组中
						// 		this.serviceId=res.services[i].uuid;
						// 		console.log(`服务id:${i}`,this.serviceId);
						// 		this.getBLEDeviceCharacteristics(deviceId, this.serviceId)//获取蓝牙设备某个服务中所有特征值
						// 		return
						// 	}
						// }

						//serviceId固定，获取蓝牙设备某个服务中所有特征值【读写属性的】
						this.getBLEDeviceCharacteristics(deviceId, this.serviceId)
					},
					fail: (err) => {
						this.connStatus = 10
						return
					}
				})
			},
			//如果一个蓝牙设备需要进行数据的写入以及数据传输，就必须具有某些特征值，所以通过上面步骤获取的id可以查看当前蓝牙设备的特征值
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				console.log(1)
				uni.getBLEDeviceCharacteristics({
					//设备id与服务id必须要给,特征值id先不用获取，直接写死
					deviceId,
					serviceId,
					success: (res) => {
						console.log('蓝牙连接:' + JSON.stringify(res))
						if (res.characteristics[0].properties.read) {
							console.log('该特征值可读');
							// console.log('该特征值可读:' + this.characteristicId);
							uni.readBLECharacteristicValue({
								deviceId,
								serviceId,
								characteristicId: this.characteristicId,
								success: (res) => {
									console.log('读取设备:', res);
								}
							});
						}
						if (res.characteristics[0].properties.write) {
							console.log('该特征值可写');
							this.canWrite = true;
							//调用写
							// this.writeBLECharacteristicValue()
						}
						//确保对应服务id下的特征值id具备监听数据变化的特性
						if (res.characteristics[0].properties.notify || res.characteristics[2].properties
							.indicate) {
							uni.notifyBLECharacteristicValueChange({
								deviceId,
								serviceId,
								characteristicId: this.characteristicId,
								state: true, //是否启用notify通知
								success: (res) => {
									console.log('通知启用(notifyBLECharacteristicValueChange)', res);
								}
							})
						}
					},
					fail(res) {
						console.error('获取蓝牙设备特征值失败(getBLEDeviceCharacteristics)', res)
					}
				})
				// 操作之前先监听，保证第一时间获取数据（value就是特征值当前最新的值）
				//监听低功耗蓝牙设备的特征值变化事件。必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification
				uni.onBLECharacteristicValueChange((characteristic) => {
					console.log('触发监听(onBLECharacteristicValueChange)');
					// console.log('原始数据:'+JSON.stringify(characteristic.value))

					// console.log('原始数据characteristicId:' + characteristic.characteristicId)
					// console.log('手机接收的原始数据：', characteristic.value);
					// console.log('手机接收的原始数据第一个字节：', this.$service.buffertoHex(characteristic.value));

					if (this.$service.buffertoHex(characteristic.value) == 0x55) {
						const dataView = new DataView(characteristic.value)

						let len = dataView.getUint8(1)
						let xorByte = dataView.getUint8(len + 2)

						const buffer1 = new ArrayBuffer(len + 1)
						const dataView1 = new DataView(buffer1)
						for (let i = 1; i <= len + 1; i++) {
							// console.log(dataView.getUint8(i))
							dataView1.setUint8(i - 1, dataView.getUint8(i))
						}

						// console.log(buffer1)

						let xor = this.$service.BytesDes(buffer1)
						console.log('xorByte:' + xorByte)
						console.log('xor:' + xor)
						if (xorByte != xor) {
							return false
						}
						// console.log(this.$service.inttoHex(dataView.getUint8(2)))
						let msg = '成功'
						let unit = 0
						let rate = 1 //1字段  小数点
						let mol

						switch (this.$service.inttoHex(dataView.getUint8(2))) {
							case 0x0A:
								console.log('9999999999')
								break
							case 0x0D:
								//提示用户滴血
								//  msg = '请往试纸滴血'
								this.connStatus = 31
								//自动连接蓝牙,打开状态
								if (this.isAutoConn) {
									this.showEchart = false;
									this.$refs['conn'].open()
								}
								return
								break
							case 0x0E:
								//当血液已经滴下进行倒计时
								// msg = '血液已经滴下进行倒计时'
								this.showEchart = false;
								this.connStatus = 32
								return
								break
							case 0x20:
								//数值显示
								//单位

								unit = this.$service.getHeight4(dataView.getUint8(3))
								rate = this.$service.getLow4(dataView.getUint8(3))

								mol = dataView.getUint8(5)

								mol = mol / (rate * 10)
								if (mol < 0.6) {
									//msg = '数值太低'
									this.connStatus = 20
									return
								}
								if (mol > 35) {
									//msg = '浓度值太高'
									this.connStatus = 21
									return
								}
								console.log('20mol:' + mol)

								this.insertData(this.deviceId, mol, unit)
								break
							case 0x21:
								//数值显示

								unit = this.$service.getHeight4(dataView.getUint8(3))
								rate = this.$service.getLow4(dataView.getUint8(3))

								mol = dataView.getUint8(5)

								mol = mol / (rate * 10)
								if (mol < 1.1) {
									//	msg = '数值太低'
									this.connStatus = 20
									return
								}
								if (mol > 33.3) {
									// 	msg = '浓度值太高'
									this.connStatus = 21
									return
								}
								console.log('21mol:' + mol)
								this.insertData(this.deviceId, mol, unit)

								break
							case 0x23:
								//温度显示
								let bai = dataView.getUint8(3) * 100
								let shi = dataView.getUint8(4)
								let t = (bai + shi) / 10
								console.log('温度:' + t)

								break
						}
						//记录手机接受的数据
						// 	this.myDataMeasure.push(this.ab2hex(characteristic.value));
						// 	//记录目前通信的对象（和谁通信，特征值是多少，初始值00）
						// 	const idx = this.inArray(this.chs, 'uuid', characteristic.characteristicId)
						// 	const data = {}

						// 	if (idx === -1) {
						// 		this.chs.push({
						// 			uuid: characteristic.characteristicId,
						// 			value: this.ab2hex(characteristic.value)
						// 		})
						// 	} else {
						// 		this.chs[idx] = {
						// 			uuid: characteristic.characteristicId,
						// 			value: this.ab2hex(characteristic.value)
						// 		}
						// 	}
					}
					//向设备发送认证A5 56 89 56
					if (characteristic.characteristicId == '000000F6-0001-0008-0000-0805F9B34FB0') {
						console.log('向设备发送认证信息')
						this.sendData = 'A5568956'
						this.writeBLECharacteristicValue()

					}


					//打印手机接收的数据的数组
					// console.log(this.myDataMeasure);

				})
			},
			insertData(deviceId, glu, unitType) {
				let _this = this
				var opt = {
					url: '/blutdruck_check/gluInsert',
					data: {
						type: 0,
						version: '1.0',
						electric: 0,
						sn: 0,
						mac: deviceId,
						glu: glu,
						unit_type: unitType
					},
					success: function(res) {
						//console.log(res)
						if (res.status) {
							_this.showEchart = true;
							_this.$refs['conn'].close()
							_this.connStatus = -1;
							//刷新数据
							_this.getData();
						} else {

							this.connStatus = 22
						}

					}
				};
				_this.$service.GetApi(opt)
			},
			//向蓝牙设备发送一个数据（期间要进行数据转换）
			writeBLECharacteristicValue() {
				console.log('我正在发送数据【手机向蓝牙模块】');
				//向蓝牙设备发送一个0x00的16进制数据//代表内存之中的一段二进制数据
				// let buffer = new ArrayBuffer()  uni.getBLEDeviceCharacteristics(OBJECT)
				// //可以自定义复合格式的视图
				// let dataView = new DataView(buffer)
				// dataView.setUint8(0, this.sendData)
				// console.log('十六进制',this.ab2hex(buffer));
				// console.log('我正在发送数据十六进制字符串:' + this.sendData);
				let buffer = this.str2ab1()
				// console.log(buffer);
				// console.log('我正在发送数据【手机向蓝牙模块】characteristicId:' + this.characteristicId);
				// console.log('我正在发送数据【手机向蓝牙模块】deviceId:' + this.deviceId);
				// console.log('我正在发送数据【手机向蓝牙模块】serviceId:' + this.serviceId);
				uni.writeBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.characteristicId,
					value: buffer,
					complete: (e) => {

						if (!this.isAutoConn) {
							this.showEchart = false;
						}

						//进入测量
						this.connStatus = 30


						//buffer本身是arraybuffer（arraybuffer要转换为16进制）
						//console.log('我正在发送数据【手机向蓝牙模块】回调',JSON.stringify(e));
						// console.log('十六进制',this.ab2str1(buffer));
						// let sixNumber=this.ab2hex(buffer);
						// console.log('二进制数组:',buffer);
						//切换特征
						this.characteristicId = '000000F5-0001-0008-0000-0805F9B34FB0'
						// console.log('切换特征deviceId:' + this.deviceId)
						// console.log('切换特征serviceId:' + this.serviceId)
						setTimeout(() => {
							this.getBLEDeviceCharacteristics(this.deviceId, this.serviceId)
						}, 1000);

					}
				})
				// console.log(999999999999)
				//this.sendData=''
			},
			//停止蓝牙设备搜寻
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery();
				//  console.log("已停止蓝牙扫描(closeBluetoothAdapter)");
				//  uni.showToast({
				// title: "蓝牙搜索已停止",
				// icon: "success",
				//  });
			},
			//关闭搜索
			closeBlueTooth() {
				uni.stopBluetoothDevicesDiscovery();
				// console.log("已关闭蓝牙搜索(closeBlueTooth)");
			},
			//关闭蓝牙适配器
			closeBluetoothAdapter() {
				uni.closeBluetoothAdapter();
				this._discoveryStarted = false;
				console.log("已关闭蓝牙适配器(closeBluetoothAdapter)");
				//清空蓝牙设备列表
				this.devices = []
				//  uni.showToast({
				// title: "适配器关闭成功",
				// icon: "success",
				//  });
			},
			//关闭蓝牙连接
			closeBLEConnection() {
				uni.closeBLEConnection({
					deviceId: this.deviceId
				});
				this.connected = false;
				this.chs = [];
				this.canWrite = false;
				// console.log("已关闭蓝牙连接(closeBLEConnection)");
				uni.showToast({
					title: "蓝牙连接已断开",
					icon: "success",
				});
			},

			touchStart(e) {
				const canvasEl = this.canvasEl
				if (!canvasEl) {
					return
				}
				canvasEl.dispatchEvent('touchstart', wrapEvent(e))
			},
			touchMove(e) {
				const canvasEl = this.canvasEl
				if (!canvasEl) {
					return
				}
				canvasEl.dispatchEvent('touchmove', wrapEvent(e))
			},
			touchEnd(e) {
				const canvasEl = this.canvasEl
				if (!canvasEl) {
					return
				}
				canvasEl.dispatchEvent('touchend', wrapEvent(e))
			},
			//测量结果说明
			testResult() {
				let _this = this
				this.$refer.setVilit('/packageHealthy/pages/device/blood-glucose/test_result')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {

				}
				this.$refer.toUrl(callback, data)
				return
			},
			//更多数据
			testRecord() {
				let _this = this
				this.$refer.setVilit('/packageHealthy/pages/test_record/test_record')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					group_id: 0,
					product_type: 2
				}
				this.$refer.toUrl(callback, data)
				return
			},
			articleDetail(id) {
				let _this = this
				this.$refer.setVilit('/packageArticle/pages/healthy-article/article_detail')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					id: id
				}
				this.$refer.toUrl(callback, data)
				return
			},
			// 文章推荐
			pageArticleList() {
				let _this = this
				this.$refer.setVilit('/packageArticle/pages/healthy-article/article_list')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				var data = {
					product_type: 2
				}
				this.$refer.toUrl(callback, data)
				return
			},
			cancelConn() {
				this.isCancel = true;
				this.isAutoConn = false;
				this.showMaskloading = false;
				this.connected = false,
					this.connStatus = -1;
				this.stopBluetoothDevicesDiscovery() //此时停止蓝牙搜索
				this.closeBLEConnection();
			}
		},
	};
</script>

<style lang="scss">
	@import "./index.scss";
</style>
